package com.jagochan.imchat.module.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jagochan.imchat.module.common.redis.RedisKey;
import com.jagochan.imchat.module.common.redis.RedisUtils;
import com.jagochan.imchat.module.common.utils.JwtUtils;
import com.jagochan.imchat.module.user.service.LoginService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.rmi.server.ObjID;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRES_DAYS = 3;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public String loginReturnToken(Long uid) {
        // 生成token
        String token = jwtUtils.createToken(uid);
        // 把token缓存到redis
        Boolean setOk = RedisUtils.set(getRedisUserTokenKey(uid), token, TOKEN_EXPIRES_DAYS, TimeUnit.DAYS);
        return token;
    }

    /**
     * 校验token是不是有效
     */
    @Override
    public boolean verifyToken(String token) {
        return false;
    }

    /**
     * 刷新token有效期
     */
    @Override
    @Async
    public void refreshTokenIfNecessary(String token) {
        Long uid = getValidUid(token);
        String key = getRedisUserTokenKey(uid);
        Long expireDays = RedisUtils.getExpire(key);
        if (expireDays == -2) { // 不存在的key
            return;
        }
        if (expireDays < 1) {
            // 续期
            RedisUtils.expire(key, TOKEN_EXPIRES_DAYS, TimeUnit.DAYS);
        }
    }

    /**
     * 如果token有效，返回uid，否则返回null
     */
    @Override
    public Long getValidUid(String token) {
        // 根据token拿出uid
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) return null;

        // 从redis中取出token
        String redisToken = RedisUtils.getStr(getRedisUserTokenKey(uid));
        if (StrUtil.isBlank(redisToken)) return null;
        if (!Objects.equals(token, redisToken)) return null;

        return uid;
    }

    private String getRedisUserTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN, uid);
    }
}
